#include "chatuserlist.h"
#include<QScrollBar>
#include<QTimer>
#include"usermgr.h"
#include<QCoreApplication>
ChatUserList::ChatUserList(QWidget *parent):QListWidget(parent),_load_pending(false)
{
    Q_UNUSED(parent);
    //设置滚动条不显示
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    //安装事件过滤器
    this->viewport()->installEventFilter(this);

}

bool ChatUserList::eventFilter(QObject *watch, QEvent *event)
{
    if(watch==this->viewport()){
        if(event->type()==QEvent::Enter){
            this->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        }
        else if(event->type()==QEvent::Leave){
            this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        }

    }

    //检查事件是否是鼠标滚轮事件
    if(watch==this->viewport()&&event->type()==QEvent::Wheel){
        QWheelEvent* wheelEvent=static_cast<QWheelEvent*>(event);
        int numDegrees=wheelEvent->angleDelta().y()/8;
        int numSteps=numDegrees/15;//设置滚轮步数
        //设置滚动幅度
        this->verticalScrollBar()->setValue(this->verticalScrollBar()->value()-numSteps);
        //检查是否滚动到底部
        QScrollBar* scrollBar=this->verticalScrollBar();
        int maxValue=scrollBar->maximum();
        int currentValue=scrollBar->value();
        if(maxValue-currentValue<=0){
            qDebug()<<"load more chat user";
            //检测是否还有数据
            auto b_loaded=UserMgr::GetInstance()->IsLoadChatFin();
            if(b_loaded){
                return true;
            }
            if(_load_pending){
                return true;
            }
            //滚动到底部，加载新的联系人
            qDebug()<<"load more chat user";
            _load_pending=true;
            QTimer::singleShot(100,[this](){
                _load_pending=false;
            });
            emit sig_loading_char_user();
        }
        return true;

    }
    return QListWidget::eventFilter(watch,event);
}
